import { Category } from '../../utils/category-model.js';
var category = new Category();
Page({

  data: {
    currentMenuIndex: 0,
    loadedData: {}
  },

  onLoad: function (options) {
    this.setData({
          adif: getApp().globalData.adif,
        });
    this._loadData();
  },

  _loadData: function () {

    category.getCategoryType((categoryData) => {

      this.setData({
        categoryTypeArr: categoryData
      });

      // 一定在回调里再进行获取分类详情的方法调用
      category.getProductsByCategory(categoryData[0].id, (data) => {
          var dataObj = {
            products: data,
            topImgUrl: categoryData[0].thumb,
            title: categoryData[0].name
          };
          this.setData({
            categoryProducts: dataObj
          })

          this.data.loadedData[0] = dataObj;
        });
    });

  },

  // 判断当前分类下的商品数据是否已经被加载过
  isLoadedData: function (index) {
    if (this.data.loadedData[index]) {
      return true;
    }
    return false;
  },

  changeCategory: function (event) {

    var index = category.getDataSet(event, 'index'),
      id = category.getDataSet(event, 'id')//获取data-set

    this.setData({
      currentMenuIndex: index
    });

    if (!this.isLoadedData(index)) {
      // 如果没有加载过当前分类的商品数据
      category.getProductsByCategory(
        id, (data) => {

          var dataObj = {
            products: data,
            topImgUrl: this.data.categoryTypeArr[index].thumb,
            title: this.data.categoryTypeArr[index].name
          };

          this.setData({
            categoryProducts: dataObj
          })

          this.data.loadedData[index] = dataObj;
        });
    }
    else {
      // 已经加载过，直接读取
      this.setData({
        categoryProducts: this.data.loadedData[index]
      })

    }
  },

  /*跳转到商品详情*/
  onProductItemTap: function (e) {
    var id = e.currentTarget.dataset["id"];
    wx.navigateTo({
      url: '../detail/detail?id=' + id
    })
  },
  onShareAppMessage (option) {
    // option.from === 'button'
    return {
      title: '点击测试【全网888万人在免费测试】',
      desc: '提供优质的智商测试、性格测试、爱情测试、趣味测试',
      path: '/pages/home/home', // ?后面的参数会在转发页面打开时传入onLoad方法
      imageUrl: '/images/logo.png', // 支持本地或远程图片，默认是小程序icon
      templateId: 'bb87ln5ge3e3cgfca8',
      success () {
        //console.log('转发发布器已调起，并不意味着用户转发成功，微头条不提供这个时机的回调');
      },
      fail () {
        //console.log('转发发布器调起失败');
      }
    }
  }
})